﻿using UnityEngine;
using System.Collections;

public class BossMoveController : MonoBehaviour
{

    private CharacterController character; // 定义人物控制器

    private Transform player; // 创建一个目标对象

    private Animator animator; // 创建动画

    public float attackDistance = 1.5f; // 怪物的攻击距离

    public float speed = 3.0f;

    public float attackTime = 2.0f;  // 怪物攻击的时间

    public float attackTimer=2.0f; // 怪物正在攻击的时间间隔 可变化的

    private bool m_move = true;

    private PlayerAttackAndDamage playerAttack;

	// Use this for initialization
	void Start () {
	character=GetComponent<CharacterController>();
        player=GameObject.FindGameObjectWithTag(Tags.player).GetComponent<Transform>();
        animator=GetComponent<Animator>();
        playerAttack=player.GetComponent<PlayerAttackAndDamage>();
	}
	
	// Update is called once per frame
	void Update () {
        if (playerAttack.hp <= 0)
        {
            animator.SetBool("Run",false);
            return;
        }


        Vector3 targetPosition = player.position;
        transform.LookAt(targetPosition);
        targetPosition.y = transform.position.y;

        float distance = Vector3.Distance(targetPosition, transform.position);

        attackTimer += Time.deltaTime;

        if (distance <= attackDistance)
        {
 
            int i=Random.Range(0, 2);
            if(attackTimer >= attackTime )
            {
                attackTimer = 0;
            if (i == 0)
            {
                animator.SetTrigger("Attack01");
            }
            else
                if (i == 1)
                {
                    animator.SetTrigger("Attack02");
                }
            }
        }
        // 如果怪物没正在攻击
        if (!(animator.GetCurrentAnimatorStateInfo(0).IsName("BossAttack01") || animator.GetCurrentAnimatorStateInfo(0).IsName("BossAttack02")))
            if (m_move)
            {
                character.SimpleMove(transform.forward * speed);
                animator.SetBool("Run", true);
            }
            else
            {
                animator.SetBool("Run", false);
            }
	}

    void OnTriggerEnter(Collider other)
    {
        if (other.tag.CompareTo("Player") == 0)
        {
            m_move = false;
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.tag.CompareTo("Player") == 0)
        {
            m_move = true;
        }
    }
}
